<?php
namespace Modules\Good\Http\Middleware;

use Closure;
use Throwable;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionHandlerMiddleware
{
    /**
     * 处理请求
     */
    public function handle($request, Closure $next)
    {
        try {
            return $next($request);
        } catch (Throwable $e) {
            // 记录日志
            Log::error('Goods Module Exception:', [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
                'request' => $request->all()
            ]);

            // 返回 JSON
            return $this->formatJson($e);
        }
    }

    /**
     * 格式化异常为 JSON
     */
    protected function formatJson(Throwable $e): JsonResponse
    {
        $status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;

        return response()->json([
            'status' => false,
            'code' => $e->getCode() ?: $status,
            'message' => app()->environment('production') ? '操作失败，请联系管理员' : $e->getMessage(),
            'error' => [
                'type' => get_class($e),
                'details' => $status >= 500 ? '服务器内部错误' : $e->getMessage()
            ]
        ], $status);
    }
}
